import { useState, memo, useTransition } from "react";

import { faker } from "@faker-js/faker";

const Color = {
  Red: "Red",
  Green: "Green",
  Blue: "Blue",
};

const products = new Array(1500).fill(null).map(() => ({
  id: faker.database.mongodbObjectId(),
  name: faker.commerce.productName(),
  description: faker.commerce.productDescription(),
  material: faker.commerce.productMaterial(),
  price: faker.commerce.price(),
  department: faker.commerce.department(),
  quantity: faker.number.int({ min: 0, max: 100 }),
  color: faker.helpers.enumValue(Color),
}));
function sleep(ms) {
  const wakeUpTime = Date.now() + ms;
  while (Date.now() < wakeUpTime) {}
}

const Products = memo(function () {
  let productsList = products.map((product, i) => (
    <SlowProduct key={product.id} product={product} />
  ));

  return (
    <>
      <h1>Products page</h1>
      <ul>{productsList}</ul>
    </>
  );
});

function SlowProduct({ product }) {
  sleep(1);
  return <li>Product {product.name}</li>;
}

function Tabs() {
  const [tab, setTab] = useState("home");
  const [isPending, startTransition] = useTransition();

  function switchTab(tab) {
    startTransition(() => {
        setTab(tab);
    })
  }

  function setStyles(thisTab) {
    return {
      backgroundColor: tab === thisTab ? "#262626" : "white",
      color: tab === thisTab ? "white" : "black",
    };
  }

  return (
    <main>
      <nav>
        <button onClick={() => switchTab("home")} style={setStyles("home")}>
          Home
        </button>
        <button
          onClick={() => switchTab("products")}
          style={setStyles("products")}
        >
          Products
        </button>
        <button onClick={() => switchTab("about")} style={setStyles("about")}>
          About
        </button>
      </nav>
      <div>
        {
            isPending && <p>Loading...</p>
        }
        {!isPending && tab === "home" && <h1>Home page</h1>}
        {!isPending && tab === "products" && <Products />}
        {!isPending && tab === "about" && <h1>About page</h1>}
      </div>
    </main>
  );
}

export default Tabs;
